package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink10_Transform_Reduce {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.通过Map将读进来的数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> result = streamSource.map(new MyMap());

        //4.将相同Id的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = result.keyBy("id");

        //TODO 5.使用Reduce实现一个Max功能
        keyedStream.reduce(new ReduceFunction<WaterSensor>() {
            /**
             *
             * @param value1 上一次聚合后的结果
             * @param value2 当前的数据
             * @return
             * @throws Exception
             */
            @Override
            public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                System.out.println("reduce...");
                return new WaterSensor(value1.getId(), value2.getTs(), Math.max(value1.getVc(), value2.getVc()));
            }
        }).print();


        env.execute();
    }

//    public static class MyMap implements MapFunction<String, WaterSensor>{
    public static class MyMap extends RichMapFunction<String, WaterSensor> {
    @Override
        public WaterSensor map(String value) throws Exception {

        String[] split = value.split(",");
            return new WaterSensor(split[0],Long.parseLong(split[1]),Integer.parseInt(split[2]));
        }
    }
}
